<template>
    <div class="page-edit">
        <PageHeader :title="formData.id ? '编辑慕课' : '创建慕课'"></PageHeader>
        <div class="page-content">
            <p class="task-notice" v-if="formData.sourceType == 'push'">该慕课由{{formData.pushDetail?.pushData?.siteName}}的{{formData.pushDetail?.pushData?.userName}}老师推送，您可以自主管理</p>
            <el-form ref="editRef" :model="formData" :rules="formRule" v-loading="loading">
                <p class="form-little-head mar-b30">慕课基本信息</p>
                <el-form-item label="慕课名称" prop="title" class="srt-el-input-item" :label-width="110">
                    <el-input show-word-limit maxlength="50" type="text" v-model="formData.title" class="srt-el-input input-width"
                        placeholder="请输入慕课名称，最多50个字">
                    </el-input>
                </el-form-item>
                <el-form-item label="慕课分类" prop="classifyList" :label-width="110">
                    <el-select v-model="formData.fType"
                        :class="['select-width', 'mr20', 'srt-select', { 'srt-clear-select': formData.fType }]" clearable
                        placeholder="请选择" size="large" popper-class="srt-select-popper" @change="changefType">
                        <el-option v-for="item in list.fTypeList" :key="item.id" :label="item.title"
                            :value="item.id" />
                    </el-select>
                    <el-select v-model="formData.sType" v-show="list.sTypeList?.length"
                        :class="['select-width', 'mr20', 'srt-select', { 'srt-clear-select': formData.sType }]" clearable
                        placeholder="请选择" size="large" popper-class="srt-select-popper" @change="changesType">
                        <el-option v-for="item in list.sTypeList" :key="item.id" :label="item.title"
                            :value="item.id" />
                    </el-select>
                    <el-select v-model="formData.tType" v-show="list.tTypeList?.length"
                        :class="['select-width', 'srt-select', { 'srt-clear-select': formData.tType }]" clearable @change="changetType"
                        placeholder="请选择" size="large" popper-class="srt-select-popper">
                        <el-option v-for="item in list.tTypeList" :key="item.id" :label="item.title"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学段/学科/年级" prop="stageSubjectList" :label-width="110">
                    <div class="subject-grade-wrap">
                        <div class="subject-el-select">
                            <stage-subject-grade-v2 
                                v-model:selectedData="formData.stageSubjectList"
                                collapseTagType="subject"
                                collapse-tags
                                clearable
                                placeholder="请选择学段学科"
                                placement="bottom-start"
                                @update:selectedData="changeGrade"
                            ></stage-subject-grade-v2>
                        </div>
                        <el-select class="grade-el-select srt-select" v-model="formData.gradeList" placeholder="请选择年级" multiple collapse-tags>
                            <el-option v-for="item in allGradeList" :label="item.name"
                            :value="item.code" :key="item.code" />
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="课程学时" prop="classHour" :label-width="110">
                    <el-input type="text" v-model="formData.classHour" class="srt-el-input input-number"
                        placeholder="请填写大于等于0的整数">
                    </el-input>
                    <!-- <span class="label">小时</span> -->
                </el-form-item>
                <el-form-item label="慕课封面" prop="cover" :label-width="110">
                    <div class="input-width">
                        <select-cover :data="realCoverList" :cur="formData.cover" :configWidth="320" :configHeight="180"
                          @select-cover="onSelectCover"></select-cover>
                        <div class="img-tip">图片尺寸 320*180，支持jpg、jpeg、png、webp格式，不超过2M</div>
                    </div>
                </el-form-item>
                <el-form-item label="慕课简介" prop="description" :label-width="110">
                    <mce-editor :value="formData.description" @update:value="formData.description = $event">
                    </mce-editor>
                </el-form-item>
                <p class="form-little-head mar-b30">主讲教师<span class="add-tip">如添加多位教师可拖拽进行排序</span></p>
                <el-form-item prop="lecturerList">
                <div>
                    <el-button v-if="formData?.lecturerList?.length < 9" class="srt-el-button srt-el-button-h36 add-btn" type="default"
                        @click="addTeacher">
                        + 添加主讲教师
                    </el-button>
                    <el-tooltip
                        v-else
                        :offset="8"
                        effect="dark"
                        content="最多添加9位教师"
                        placement="bottom"
                      >
                        <el-button class="srt-el-button-h36 disabled-btn">+ 添加主讲教师</el-button>
                    </el-tooltip>
                    <draggable :animation="500"
                        v-if="formData.lecturerList?.length"
                        :class="['teacher-list']"
                        :list="formData.lecturerList"
                        group="teacher-list"
                        ghost-class="ghost"
                        drag-class="chosen"
                        :options="{ draggable: '.teacher-item' }">
                        <LectureItem
                            class="teacher-item"
                            v-for="(item, index) in formData.lecturerList" 
                            :key="index"
                            :data="item"
                            @add-lecture="addTeacher"
                            @delete-lecture="() =>{deleteTeacher(index)}"></LectureItem>
                    </draggable>
                </div>
            </el-form-item>
            </el-form>
        </div>
        <FooterSubmit :loading="loading" @cancel="cancel" @submit="save"/>
        <LectureDialog v-model="showDialog" :form="lectureInfo" @update-lecture="updateLecture" />
    </div>
</template>
<script setup>
import { VueDraggableNext as draggable } from "vue-draggable-next";
import PageHeader from './part/page-header.vue';
import MceEditor from '@/components/mceEditor/index.vue';
import SelectCover from './part/select-cover.vue';
import StageSubjectGradeV2 from '@/components/stage-subject/stage-subject-grade-v2.vue';
import LectureDialog from '@/views/design/part/dialog/lecture-dialog.vue';
import FooterSubmit from '@/components/common-footer-submit.vue';
import LectureItem from './part/lecture-item.vue';
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { jumpHref } from '@/router/jumpHref';
import { useStore } from 'vuex';
import ImgHead from '@/assets/img/mooc/img-head.png';
import Confirm from '@/components/confirm/confirm.js';

const route = useRoute();

const store = useStore();

const formRule = ref({
    title: [
        {
            required: true,
            validator: (rule, value, callback) => {
                let temp = value && value.trim() || '';
                if (temp.length > 50 || temp.length < 2) {
                    callback('请输入2-50个字的慕课名称');
                }else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    description: [
        { required: false, message: '请填写慕课简介', trigger: 'blur' },
    ],
    cover: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (value) {
                    callback();
                } else {
                    callback(new Error('请选择封面'));
                }
            },
            trigger: 'none'
        }
    ],
    classifyList: [
        { required: true, message: '请选择慕课分类', len: 1, trigger: 'change', type: 'array' }
    ],
    classHour: [
        {
            required: false,
            validator: (rule, value, callback) => {
                let temp = Number(value);
                if (value && !/^[0-9]\d*$/.test(temp) || value > 100) {
                    callback('请输入0-100的整数');
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    // stageSubjectList: [
    //     {
    //         required: true,
    //         validator: (rule, value, callback) => {
    //             if (
    //                 formData.value.stageSubjectList &&
    //                 formData.value.stageSubjectList.length > 0
    //             ) {
    //                 callback();
    //             } else {
    //                 callback(new Error('请选择学段学科'));
    //             }
    //         },
    //         trigger: 'none'
    //     }
    // ]
});

const list = reactive({
    fTypeList: [],
    sTypeList: [],
    tTypeList: [],
    coverList: [], // 封面列表
    
})

// 表单对象
const formData = ref({
    stageSubjectList: [], // 学段学科列表
    gradeList: [], // 年级列表
    lecturerList: [] // 
});

// 讲师弹窗
const showDialog = ref(false);

// 讲师信息
const lectureInfo = ref({});

const lectureConfirmVisible = ref([]);


// 封面列表
const realCoverList = computed(() => {
    let arr = list.coverList || [];
    if (formData.value.cover) {
        let index = arr.findIndex((item) => {
            return item === formData.value.cover;
        });
        if (index === -1) {
            arr.push(formData.value.cover);
        }
    }
    return arr;
})

// 年级列表
const allGradeList = computed(() => {
    const ids = (formData.value.stageSubjectList || []).map(item => Number(item.stageId));
    const list = (store.state.common.allStageRefSubject ||  [])
        .filter(item => ids.includes(item.stage))
        .map(item => item.grades && item.grades.map(g => ({...g, pid: item.stage})) || [])
        .flat();
    return list.filter(item => item.code != 9999);
})


// 选择封面图
function onSelectCover (url) {
    formData.value.cover = url;
}

// 修改第一个类型
function changefType () {
    let fTypeObj = list.fTypeList.find(item => item.id === formData.value.fType) || {};
    list.sTypeList = fTypeObj.child || [];
    list.tTypeList = [];
    formData.value.sType = '';
    formData.value.tType = '';
    if(fTypeObj.id) {
        formData.value.classifyList = [Object.assign({}, fTypeObj, {name: fTypeObj.title})];
    }else {
        formData.value.classifyList = [];
    }
}

// 修改第二个类型
function changesType () {
    let fTypeObj = list.sTypeList.find(item => item.id === formData.value.sType) || {};
    list.tTypeList = fTypeObj.child || [];
    formData.value.tType = '';
    if(fTypeObj.id) {
        formData.value.classifyList[0].children = [Object.assign({}, fTypeObj, {name: fTypeObj.title})];
    }else {
        formData.value.classifyList[0].children = [];
    }
}

// 修改第三个类型
function changetType() {
    let fTypeObj = list.tTypeList.find(item => item.id === formData.value.tType) || {};
    if(fTypeObj.id) {
        formData.value.classifyList[0].children[0].children = [Object.assign({}, fTypeObj, {name: fTypeObj.title})];
    }else {
        formData.value.classifyList[0].children[0].children = [];
    }
}


const loading = ref(false);

const editRef = ref(null);


// 提交保存
function save () {
   
    if (formData.value.id && !(formData.value.state === 1 || formData.value.state === 3)) {
        let message = formData.value.publishState === 1 && formData.value.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }
    editRef.value.validate((valid) => {
        if (!valid) {
            G_dispatchEvent('toast', { message: '请检查必填信息', type: 'error' })
            return;
        }
        loading.value = true;
        let portalName = formData.value.id ? 'moocUpdate' : 'moocCreate';
        const gradeList = allGradeList.value && allGradeList.value.length && allGradeList.value.filter(item => formData.value.gradeList.includes(item.code)).map(item => ({gradeId: item.code, gradeName: item.name})) || [];
        let params = {
            state: 1,
            ...formData.value,
            bizId: 0,
            bizScene: 'mooc',
            gradeList
        }
        params.stageSubjectList = params.stageSubjectList || [];
        if (params.stageSubjectList && params.stageSubjectList.length <= 0) {
            delete params.stageSubjectList
        }
        if (params.gradeList && params.gradeList.length <= 0) {
            delete params.gradeList
        }
        G_transmit(portalName, {
            data: params
        })
        .then((res) => {
            let tip = formData.value.id ? '编辑成功' : '创建成功';
            G_dispatchEvent('toast', { message: tip, type: 'success' });
            backMoocEdit(formData.value.id ? formData.value.id : res.data);
        })
        .catch((_err) => {
            console.log(_err)
        }).finally(() => {
            loading.value = false;
        });
    })
}

// 返回 慕课列表
function backMoocList() {
    let url = getMoocListUrl();
    G_go(url);
}

function getMoocListUrl() {
    let query = window.location.search.substring(1);
    return jumpHref.mooc.moocList(query);
}

// 返回慕课编辑
function backMoocEdit (id) {
    let query = window.location.search.substring(1);
    let vars = query.split("&");
    let len = vars.length;
    let queryObj = {}
	for (let i = 0; i < len; i++) {
	    let pair = vars[i].split("=");
        queryObj[pair[0]] = pair[1];
    }
    G_go({name: 'manage', query: queryObj, params: { moocId: id}});
}

// 取消
function cancel () {
    if (route.params.moocId) { // 编辑慕课 返回慕课管理-编辑慕课
        backMoocEdit(route.params.moocId);
    } else { // 新建慕课 返回慕课管理
        backMoocList();
    }
}


// 获取详情
function getDetail () {
    loading.value = true;
    G_transmit('moocDetail', {
        queries: {
            id: route.params.moocId
        },
        silence: true
    }).then((res) => {
        let result = res.data || {};
        result.gradeList = result.gradeList && result.gradeList.length && result.gradeList.map(item => item.gradeId) || [];
        result.stageSubjectList = result.stageSubjectList || [];
        result.lecturerList = result.lecturerList || [];
        formData.value = result;
        if(!formData.value.isMyCreate) { // 不是创建人
            G_dispatchEvent('toErrorPage', { title: '很抱歉，您暂时没有权限对该慕课进行编辑', code: 500, buttonLabel: '返回', target: getBackUrl()});
        }
        changeFormType();
    }).catch((_err) => {
       const { status } = _err;
       if(status.code === 30800404) {
           G_dispatchEvent('toErrorPage', { title: '该慕课可能已经被删除', code: 500, buttonLabel: '返回', target: getBackUrl()});
           return;
       }
       G_dispatchEvent('toast', { message: status.desc, type: 'error' });
    }).finally(() => {
        loading.value = false;
    });
}

// 格式化分类
function changeFormType() {
    
    let newClassifyList = [];
    let fType, sType, tType = '';
    let tempList = formData.value.classifyList || [];
    let fTypeObj = tempList.length && tempList[0] || {};
    // 一类
    fType = fTypeObj.id;
    // 二类
    sType = fTypeObj?.children?.length && fTypeObj.children[0].id || '';
    // 三类
    tType = sType && fTypeObj.children[0].children?.length && fTypeObj.children[0].children[0].id || '';

    // 一类
    let newFtype = list.fTypeList.find(item => item.id === fType);
    list.sTypeList = newFtype?.child || [];
     // 二类
    let newStype = list.sTypeList.find(item => item.id === sType);
    list.tTypeList = newStype?.child || [];
     // 三类
    let newTtype = list.tTypeList.find(item => item.id === tType);

    newClassifyList = [Object.assign({}, newFtype, {name: newFtype.title})];
    if(newFtype && newStype) {
        newClassifyList[0].children = [Object.assign({}, newStype, {name: newStype.title})];
    }
    if(newStype && newTtype) {
        newClassifyList[0].children[0].children = [Object.assign({}, newTtype, {name: newTtype.title})];
    }
    formData.value.fType = newFtype?.id || '';
    formData.value.sType = newStype?.id || '';
    formData.value.tType = newTtype?.id || '';
    formData.value.classifyList = newClassifyList;
}

// 封面列表
function getCoverList () {
    G_transmit('moocCoverList', {
        queries: {
            id: route.params.moocId
        }
    }).then((res) => {
        list.coverList = res.data || [];
        if(!route.params.moocId) {
            formData.value.cover = list.coverList[0];
        }
    }).catch((_err) => {

    })
}


// 分类列表
function getClassifyList () {
    return G_transmit('classifyList', {
        queries: {
            type: 'mooc'
        }
    }).then((res) => {
        list.fTypeList = res.data || [];
    }).catch((_err) => {

    })
}

// 添加老师
function addTeacher (data = {}) {
    lectureInfo.value = data;
    showDialog.value = true;
}

// 删除老师
function deleteTeacher(index) {
    formData.value.lecturerList.splice(index, 1);
    G_dispatchEvent('toast', { message: '删除成功', type: 'success' });
    // Confirm(
    //     { 
    //         title: '温馨提示', 
    //         text: '删除后不可撤销，确定要删除吗？'
    //     }
    // )
    // .then(ret => {
    //     formData.value.lecturerList.splice(index, 1);
    // })
    // .catch(_err => {
    //     console.log(_err);
    // }) 
}

// 更新老师
function updateLecture(data) {
    let index = formData.value.lecturerList.findIndex(item => item.id === data.id);
    if(index === -1) {
       formData.value.lecturerList.push(data);
    }else {
       formData.value.lecturerList[index] = data;
    }
}

function changeGrade() {
    formData.value.gradeList = [];
}



onMounted(async () => {
    getCoverList();
    await getClassifyList();
    if(route.params.moocId) {
        getDetail();
    }
})

// watch(() => allGradeList.value, (val) => {
//     let grades = allGradeList.value.filter(item => formData.value.gradeList.includes(item.code))
//     formData.value.gradeList = grades.map(item => item.code)
// }, {deep: true})




</script>

<style lang="scss" scoped>
.page-edit {
    padding-bottom: 30px;
}
.page-content {
    margin-top: 20px;
    background: #ffffff;
    padding: 20px 20px 10px;
    border-radius: 4px;
    // margin-bottom: 30px;
    .form-little-head {
        display: flex;
        align-items: center;
        font-size: 14px;
        font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
        font-weight: bold;
        color: #222222;
        line-height: 22px;
        margin-bottom: 24px;
        &::before {
            content: '';
            display: inline-block;
            width: 3px;
            height: 14px;
            background: #028AFF;
            vertical-align: middle;
            margin-right: 8px;
        }
        .add-tip {
            font-size: 12px;
            font-weight: 400;
            color: var(--srt-color-light-gray);
            margin-left: 12px;
            display: inline-block;
        }
    }
    .add-btn,
    .disabled-btn {
        width: 138px;
        margin-left: 10px;
    }
    .disabled-btn {
        color: #B2DAFC;
        border: 1px solid #B2DAFC;
        cursor: not-allowed;
        &:hover {
            color: #B2DAFC;
            border: 1px solid #B2DAFC;
            background: #ffffff;
        }
    }
    .mar-b30 {
        margin-bottom: 30px;
    }
    
    :deep(.el-form-item) {
        margin-bottom: 24px;
    }
    :deep(.el-form-item__label) {
        line-height: 40px;
        height: 40px;
        color: var(--srt-color-gray);
        margin-right: 8px;
    }
    :deep(.mce-editor-wrap) {
        width: 915px;
    }
    .label {
        color: var(--srt-main-text-color);
    }
    .img-tip {
        font-size: 14px;
        margin: -8px 0px 0px;
        line-height: 1;
        color: var(--srt-color-light-gray);
    }
    :deep(.mce-panel) {
        border-color: #E0E2E4 !important;
    }
    :deep(.mce-tinymce) {
        box-shadow: none;
        border-radius: 4px;
    }
    :deep(.mce-top-part::before) {
        box-shadow: none;
    }
    .subject-grade-wrap {
        display: flex;
        height: 40px;
        :deep(.ss) {
            line-height: 40px;
        }
    }
    .subject-el-select {
        width: 460px;
    }
    .grade-el-select{
        width: 220px;
        margin-left: 20px;
        :deep(.el-input) {
            height: 40px;
        }
        :deep(.el-tag){
            padding: 13px 8px;
            font-size: 14px;
            color: var(--color-light-black);
            background: #EFF0F2;
            border-radius: 2px;
            margin-right: 4px;
            display: inline-flex;
            align-items: center;
        }
    }
    .teacher-list {
        display: flex;
        flex-wrap: wrap;
        margin-top: 20px;
        li {
            width: 336px;
            height: 160px;
            background: #F7F9FA;
            border-radius: 5px;
            display: flex;
            padding: 14px;
            margin-bottom: 20px;
            margin-right: 16px;
            position: relative;
            border: 1px solid #F7F9FA;
            &:nth-child(3n) {
                margin-right: 0px;
            }
            &:nth-child(3n+1):nth-last-child(-n+3),
            &:nth-child(3n+1):nth-last-child(-n+3)~.li{
                margin-bottom: 0;
            }
            &:hover {
                border: 1px solid #E4E9EE;
            }
        }
        
    }
}
.input-number {
    width: 220px;
    margin-right: 11px;
}
.input-width {
    width: 915px;
}
.select-width {
    width: 220px;
}
.mr20 {
   margin-right: 20px;
}
.task-notice {
        font-size: 14px;
        color: #7A5F45;
        height: 50px;
        background: #FFF8EE;
        border-radius: 4px;
        border: 1px solid #FFDDAF;
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        &::before {
            content: '\e6a8';
            color: var(--srt-color-warning);
            font-size: 24px;
            font-family: 'iconfont';
            margin: 0 10px 0 20px;
        }
        .orange-font {
            color: var(--srt-color-warning);
            margin: 0 4px;
        }
    }
</style>